﻿/****************************************************************
*   作者：Morain
*   创建时间：2018/2/26 16:20:58
*   描述说明：
*****************************************************************/
using System;
using System.Collections.Generic;
using System.Text;

namespace ETSModel
{
  /// <summary>
  /// 消息处理
  /// </summary>
  public abstract class AMHandler<Request, Response> : IMHandler where Request : class, IRequest where Response : class, IResponse
  {
    public Type GetMessageType()
    {
      return typeof(Request);
    }

    public void Handle(Session session, uint rpcId, IMessage message)
    {
      try
      {
        Request request = message as Request;
        if (request == null)
        {
          Log.Error($"消息类型转换错误: {message.GetType().Name} to {typeof(Request).Name}");
        }

        this.Run(session, request, response =>
        {
          if (session.Id == 0)
            return;
          session.Reply(rpcId, response);
        });

      }
      catch (Exception e)
      {
        throw new Exception($"解释消息失败: {message.GetType().FullName}", e);
      }
    }

    protected void ReplyError(Response response, Exception e, Action<Response> reply)
    {
      Log.Error(e.ToString());
      response.Error = ErrorCode.ERR_RpcFail;
      response.Message = e.ToString();
      reply(response);
    }

    protected abstract void Run(Session session, Request message, Action<Response> reply);
  }
}
